package com.project.modules.manage;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.common.api.CommonPage;
import com.project.common.api.CommonResult;
import com.project.modules.manage.vo.*;
import com.project.modules.notice.model.TblMessage;
import com.project.modules.notice.service.TblMessageService;
import com.project.modules.redEnvelope.model.TblRecord;
import com.project.modules.redEnvelope.model.TblRedEnvelope;
import com.project.modules.redEnvelope.model.TblSign;
import com.project.modules.redEnvelope.service.TblRecordService;
import com.project.modules.redEnvelope.service.TblRedEnvelopeService;
import com.project.modules.redEnvelope.service.TblSignService;
import com.project.modules.ums.dto.UmsUserLoginParam;
import com.project.modules.ums.dto.UmsUserParam;
import com.project.modules.ums.model.UmsUser;
import com.project.modules.ums.model.UmsUserLoginLog;
import com.project.modules.ums.service.UmsRoleService;
import com.project.modules.ums.service.UmsUserLoginLogService;
import com.project.modules.ums.service.UmsUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Josh-ZJUT
 * @date 2023/9/10 10:26
 * @email dujianghui537885@163.com
 */
@RequestMapping("/manage")
@RestController
@Api(value = "ManageController", tags = "【管理端】")
@Slf4j
public class ManageController {
    @Autowired
    private UmsUserService userService;
    @Autowired
    private UmsRoleService roleService;
    @Autowired
    private TblSignService signService;
    @Autowired
    private TblRecordService recordService;
    @Autowired
    private TblRedEnvelopeService redEnvelopeService;
    @Autowired
    private UmsUserLoginLogService userLoginLogService;
    @Autowired
    private TblMessageService messageService;
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @ApiOperation("用户信息")
    @GetMapping("/user")
    public CommonResult<CommonPage<UserManageVo>> getUserManageVoPage(@RequestParam(value = "keyword", required = false) String keyword,
                                                                      @RequestParam(value = "belongto", required = false) String belongto,
                                                                      @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                                                      @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        IPage<UserManageVo> userList = userService.getPage(keyword, belongto, pageSize, pageNum).convert(umsUser -> {

            final Long userId = umsUser.getId();
            final UmsUser belongtoUser = userService.getByUsername(umsUser.getBelongTo());
            String group = "";
            if (belongtoUser != null) {
                group = belongtoUser.getNickName();
            }
            final String role = roleService.getById(umsUser.getRoleId()).getName();
            final Long count = signService.count(new LambdaQueryWrapper<TblSign>().eq(TblSign::getUserId, userId));
            final BigDecimal getAmount = recordService.list(new LambdaQueryWrapper<TblRecord>().eq(TblRecord::getReceviceUserId, userId))
                    .stream().map(TblRecord::getReceiveAmount).filter(amount -> amount != null)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            final BigDecimal sendAmount = redEnvelopeService.list(new LambdaQueryWrapper<TblRedEnvelope>().eq(TblRedEnvelope::getCreateBy, umsUser.getUsername()))
                    .stream().map(TblRedEnvelope::getTotalAmount).filter(amount -> amount != null)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);

            return UserManageVo.builder()
                    .id(userId)
                    .nickname(umsUser.getNickName())
                    .name(umsUser.getUsername())
                    .money(umsUser.getAccountBalance())
                    .group(group)
                    .role(role)
                    .phone(umsUser.getPhone())
                    .activityCount(count)
                    .getAmount(getAmount)
                    .sendAmount(sendAmount)
                    .build();
        });
        log.info(userList.getTotal() + "");
        return CommonResult.success(CommonPage.restPage(userList));
    }

    @ApiOperation("黑名单信息")
    @GetMapping("/black")
    public CommonResult<CommonPage<BlackListManageVo>> getBlackPage(@RequestParam(value = "keyword", required = false) String keyword,
                                                                    @RequestParam(value = "blackType", required = false) String blackType,
                                                                    @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                                                    @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {

        LambdaQueryWrapper<UmsUser> wrapper = new LambdaQueryWrapper<UmsUser>().eq(UmsUser::getBlack, 1);
        if (StrUtil.isNotEmpty(keyword)) {
            wrapper.like(UmsUser::getUsername, keyword);
            wrapper.or().like(UmsUser::getNickName, keyword);
        }
        wrapper.eq(StrUtil.isNotEmpty(blackType), UmsUser::getBlackType, blackType);

        final IPage<BlackListManageVo> convert = userService.page(new Page<>(pageNum, pageSize), wrapper)
                .convert(umsUser -> {
                    final Long userId = umsUser.getId();

                    return BlackListManageVo.builder()
                            .id(userId)
                            .nickname(umsUser.getNickName())
                            .name(umsUser.getUsername())
                            .money(umsUser.getAccountBalance())
                            .phone(umsUser.getPhone())
                            .withdraw(umsUser.getWithdrawAmount())
                            .blackType(umsUser.getBlackType())
                            .blackReason(umsUser.getBlackReason())
                            .build();
                });
        log.info(convert.getTotal() + "");
        return CommonResult.success(CommonPage.restPage(convert));

    }

    @ApiOperation("活动id和名称")
    @GetMapping("/record/activity")
    public CommonResult<List<ActivityListManageVo>> getActivityList() {
        return CommonResult.success(redEnvelopeService.list().stream().map(
                redEnvelope -> ActivityListManageVo.builder()
                        .activityName(redEnvelope.getActivityName())
                        .id(redEnvelope.getId())
                        .build()).collect(Collectors.toList()));
    }

    @ApiOperation("查询所有消息")
    @GetMapping("/messageList")
    public CommonResult<List<MessageUserManegeVo>> getMessageList(@RequestParam(value = "redId", required = false) Long redId) {
        return CommonResult.success(
                messageService.list(new LambdaQueryWrapper<TblMessage>()
                                .eq(redId != null, TblMessage::getRedId, redId))
                        .stream().map(tblMessage ->
                                new MessageUserManegeVo(tblMessage.getReceiveUserId(),
                                        userService.getById(tblMessage.getReceiveUserId()).getNickName())).collect(Collectors.toList()));
    }

    @ApiOperation("红包记录信息")
    @GetMapping("/record")
    public CommonResult<CommonPage<RecordManageVo>> getRecordPage(
            @RequestParam(value = "redId", required = false) Long redId,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        LambdaQueryWrapper<TblRecord> wrapper = new LambdaQueryWrapper<TblRecord>()
                .eq(redId != null, TblRecord::getRedId, redId)
                .orderByDesc(TblRecord::getReceiveAmount);
        final IPage<RecordManageVo> convert = recordService.page(new Page<>(pageNum, pageSize), wrapper)
                .convert(tblRecord -> {
                    final TblRedEnvelope envelope = redEnvelopeService.getById(tblRecord.getRedId());
                    return RecordManageVo.builder()
                            .id(tblRecord.getId())
                            .activityName(envelope.getActivityName())
                            .sendUser(userService.getByUsername(envelope.getCreateBy()).getNickName())
                            .receiveUser(userService.getById(tblRecord.getReceviceUserId()).getNickName())
                            .receiveAmount(tblRecord.getReceiveAmount())
                            .score(tblRecord.getScore())
                            .icon(userService.getById(tblRecord.getReceviceUserId()).getIcon())
                            .createTime(tblRecord.getCreateTime())
                            .build();
                });
        log.info(convert.getTotal() + "");
        return CommonResult.success(CommonPage.restPage(convert));
    }

    @ApiOperation("用户登陆记录信息")
    @GetMapping("/loginRecord")
    public CommonResult<CommonPage<LoginRecordManageVo>> getLoginRecordPage(
            @RequestParam(value = "keyword", required = false) String keyword,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        LambdaQueryWrapper<UmsUserLoginLog> wrapper = new LambdaQueryWrapper<UmsUserLoginLog>();

        if (StrUtil.isNotEmpty(keyword)) {
            wrapper.like(UmsUserLoginLog::getUsername, keyword);
            wrapper.or().like(UmsUserLoginLog::getNickName, keyword);
        }

        final IPage<LoginRecordManageVo> convert = userLoginLogService.page(new Page<>(pageNum, pageSize), wrapper)
                .convert(umsUserLoginLog -> LoginRecordManageVo.builder()
                        .username(umsUserLoginLog.getUsername())
                        .ip(umsUserLoginLog.getIp())
                        .nickname(umsUserLoginLog.getNickName())
                        .address(umsUserLoginLog.getAddress())
                        .userAgent(umsUserLoginLog.getUserAgent())
                        .loginTime(umsUserLoginLog.getCreateTime())
                        .build());
        return CommonResult.success(CommonPage.restPage(convert));
    }

    @ApiOperation("红包活动信息，根据活动名称或活动状态查询")
    @GetMapping("/activity")
    public CommonResult<CommonPage<RedEnvelopeManageVo>> getActivityPage(
            @RequestParam(value = "activityName", required = false) String activityName,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        LambdaQueryWrapper<TblRedEnvelope> wrapper = new LambdaQueryWrapper<TblRedEnvelope>()
                .like(StrUtil.isNotEmpty(activityName), TblRedEnvelope::getActivityName, activityName)
                .eq(status != null, TblRedEnvelope::getStatus, status);
        final IPage<RedEnvelopeManageVo> convert = redEnvelopeService.page(new Page<>(pageNum, pageSize), wrapper)
                .convert(redEnvelope -> {
                    final UmsUser sendUser = userService.getByUsername(redEnvelope.getCreateBy());
                    String sendUserNickName = "";
                    if (sendUser != null) {
                        sendUserNickName = sendUser.getNickName();
                    }
                    return RedEnvelopeManageVo.builder()
                            .redId(redEnvelope.getId())
                            .activityName(redEnvelope.getActivityName())
                            .sendUser(sendUserNickName)
                            .money(redEnvelope.getTotalAmount())
                            .headCountLimit(redEnvelope.getHeadCountLimit())
                            .signCount(signService.count(new LambdaQueryWrapper<TblSign>().eq(TblSign::getRedId, redEnvelope.getId())))
                            .startTime(redEnvelope.getStartTime())
                            .duration(DateUtil.between(redEnvelope.getStartTime(), redEnvelope.getEndTime(), DateUnit.SECOND))
                            .notifyEmail("是")
                            .notifyMessage("是")
                            .status(redEnvelope.getStatus())
                            .picture(redEnvelope.getPicture())
                            .content(redEnvelope.getContent())
                            .build();
                });
        return CommonResult.success(CommonPage.restPage(convert));
    }

    @ApiOperation("消息管理，根据活动名称或活动状态查询")
    @GetMapping("/message")
    public CommonResult<CommonPage<MessageManageVo>> getMessagePage(
            @RequestParam(value = "activityName", required = false) String activityName,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        LambdaQueryWrapper<TblRedEnvelope> wrapper = new LambdaQueryWrapper<TblRedEnvelope>()
                .like(StrUtil.isNotEmpty(activityName), TblRedEnvelope::getActivityName, activityName)
                .eq(status != null, TblRedEnvelope::getStatus, status);
        final IPage<MessageManageVo> convert = redEnvelopeService.page(new Page<>(pageNum, pageSize), wrapper)
                .convert(redEnvelope -> {
                    final UmsUser sendUser = userService.getByUsername(redEnvelope.getCreateBy());
                    String sendUserNickName = "";
                    if (sendUser != null) {
                        sendUserNickName = sendUser.getNickName();
                    }

                    String content = "";
                    long emailCount = 0, messageCount = 0;
                    Date sendTime = null;
                    final List<TblMessage> messages = messageService.list(new LambdaQueryWrapper<TblMessage>().eq(TblMessage::getRedId, redEnvelope.getId()));
                    if (CollectionUtil.isNotEmpty(messages)) {
                        sendTime = messages.get(0).getSendTime();
                        content = messages.get(0).getContent();
                        for (TblMessage message : messages) {
                            if (message.getMethod().equals(1)) {
                                messageCount++;
                            } else if (message.getMethod().equals(2)) {
                                emailCount++;
                            }
                        }
                    }
                    return MessageManageVo.builder()
                            .redId(redEnvelope.getId())
                            .activityName(redEnvelope.getActivityName())
                            .sendUser(sendUserNickName)
                            .content(content)
                            .emailCount(emailCount)
                            .messageCount(messageCount)
                            .sendTime(sendTime)
                            .build();
                });
        return CommonResult.success(CommonPage.restPage(convert));
    }

    @ApiOperation("初始化用户")
    @GetMapping("/initUser")
    public CommonResult<Object> initUser() {

//        userLoginLogService.remove(Wrappers.emptyWrapper());
        if (userService.getByUsername("13758161316") == null) {
            userService.register(new UmsUserParam("13758161316", "123456",
                    "https://photo.16pic.com/00/34/27/16pic_3427939_b.jpg", "13758161316", "dujianghui_work@163.com", "都将会"
                    , "个人", 4L));
        }
        if (userService.getByUsername("17857699406") == null) {
            userService.register(new UmsUserParam("17857699406", "123456",
                    "https://img2.baidu.com/it/u=1553721018,1810382361&fm=253&fmt=auto&app=138&f=JPEG?w=400&h=400", "17857699406", "123124681@163.com", "尖头man"
                    , "个人", 4L));
        }
        if (userService.getByUsername("15312345678") == null) {
            userService.register(new UmsUserParam("15312345678", "123456",
                    "https://i.75ll.com/up/15/1c/c5/7aff47097cd880084dfcb650d3c51c15.jpg", "15312345678", "user@qq.com", "Martin"
                    , "个人", 4L));
        }
        if (userService.getByUsername("17367115870") == null) {
            userService.register(new UmsUserParam("17367115870", "123456",
                    "https://wx3.sinaimg.cn/mw690/007ILrdtly1hg5z239fw4j30j60j3abw.jpg", "17367115870", "user@qq.com", "余止欺"
                    , "个人", 4L));
        }
        if (userService.getByUsername("13758195874") == null) {
            userService.register(new UmsUserParam("13758195874", "123456",
                    "https://img.touxiangwu.com/zb_users/upload/2022/10/202210011664639037820567.jpg", "13758195874", "user@qq.com", "高康"
                    , "个人", 4L));
        }

        if (userService.getByUsername("tailong") == null) {
            userService.register(new UmsUserParam("tailong", "123456",
                    "https://is5-ssl.mzstatic.com/image/thumb/Purple126/v4/14/1a/7c/141a7cba-2879-517d-1af6-b8a46cba6528/AppIcon-1x_U007emarketing-0-5-0-0-sRGB-85-220.png/512x512bb.jpg", "95347", "hello@tailong.com", "泰隆银行"
                    , "泰隆银行", 3L));
        }

        if (userService.getByUsername("zjut") == null) {
            userService.register(new UmsUserParam("zjut", "123456",
                    "https://www.ygb.sdu.edu.cn/__local/3/0F/29/9DBD25542535CD875BF7BF860F9_F2FDACC9_1893E.jpg", "0571-88320114", "2112112146@zjut.edu.cn", "浙江工业大学"
                    , "浙江工业大学", 3L));
        }


        if (userService.getByUsername("company") == null) {
            userService.register(new UmsUserParam("company", "123456",
                    "https://pic.vjshi.com/2022-03-24/aa94219371ce4d1ab797767f0d4dc45a/online/main.jpg?x-oss-process=style/w342_h192_center",
                    "13579246810", "2112112146@zjut.edu.cn", "浙江税硕沃能力有限公司"
                    , "浙江税硕沃能力有限公司", 3L));
        }


        final String token = userService.login(new UmsUserLoginParam("13758161316", "123456"));
        return CommonResult.success(tokenHead + token);
    }

    @ApiOperation("【慎点】初始化活动")
    @GetMapping("/initRedEnvelopes")
    public CommonResult<Object> initRedEnvelopes() {
        recordService.remove(Wrappers.emptyWrapper());
        redEnvelopeService.remove(Wrappers.emptyWrapper());
        signService.remove(Wrappers.emptyWrapper());
        messageService.remove(Wrappers.emptyWrapper());
        return CommonResult.success();
    }
}
